package com.tiyende.kash.loop.ui.fragment

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Handler
import android.os.Looper
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.graphics.toColorInt
import com.lib.common.permission.CommonPermissions
import com.lib.common.permission.OnPermissionCallback
import com.lib.common.permission.Permission
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.common.CommonFragment
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.databinding.TiyendeFragmentAuthenticationStepCardInfoBinding
import com.tiyende.kash.loop.event.TiyendeEventData
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.ui.activity.TiyendeAuthenticationStepsActivity
import com.tiyende.kash.loop.ui.activity.TiyendeCameraCardActivity
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.dialog.TiyendePermissionReasonDialog
import com.tiyende.kash.loop.ui.dialog.TiyendePhotoDialog
import com.tiyende.kash.loop.ui.dialog.TiyendeSuccessDialog
import com.tiyende.kash.loop.ui.presenter.TiyendeImageUploadPresenter
import com.tiyende.kash.loop.utils.TiyendeImageUtil
import com.tiyende.kash.loop.utils.helper.TiyendePermissionHelper
import com.tiyende.kash.loop.utils.imgcovert.ImageConvert
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import com.tiyende.kash.loop.utils.track.TrackPointManager
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 10:38
 * @Annotation：认证流程 - PAN Card || Aadhaar Card
 */
class TiyendeAuthenticationStepCardInfoFragment(): CommonFragment(), IViewContract.ITiyendeImageUploadView {
    private var _binding: TiyendeFragmentAuthenticationStepCardInfoBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "tiyende kash card info binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )
    private var stepItem: JSONObject? = null
    private var stepTitle = ""

    private var upLoadPresenter: TiyendeImageUploadPresenter? = null
    private var photoDialog: TiyendePhotoDialog? = null
    //是否是正面
    private var isFront = true
    //正面照
    private var imgFrontUrl = ""
    //背面照
    private var imgBackUrl = ""
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>
    //是否选中删除信息,默认选中
    private var isShowDelete = true

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
        stepTitle = stepItem.optString("stepTitle")
    }

    override fun getTiyendeRootView(inflater: LayoutInflater): View {
        _binding = TiyendeFragmentAuthenticationStepCardInfoBinding.inflate(inflater)
        return binding.root
    }

    override fun initTiyendeView() {
        isShowDelete = true
        showTiyendeCardInfoDeleteTips()
        stepItem?.let {
            val cardTitle = it.optString("showTitle")
            val showFrontPhotoText = String.format(getString(R.string.tiyende_authentication_step_card_photo_tips),getString(R.string.tiyende_authentication_step_card_front),cardTitle)
            val showBackPhotoText = String.format(getString(R.string.tiyende_authentication_step_card_photo_tips),getString(R.string.tiyende_authentication_step_card_back),cardTitle)

            val frontSpannableString = SpannableString(showFrontPhotoText)
            val startFrontIndex = showFrontPhotoText.indexOf(getString(R.string.tiyende_authentication_step_card_front))
            val startCardTitleIndex = showFrontPhotoText.indexOf(cardTitle)
            frontSpannableString.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startFrontIndex, startFrontIndex + getString(R.string.tiyende_authentication_step_card_front).length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            frontSpannableString.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startCardTitleIndex, startCardTitleIndex + cardTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            frontSpannableString.setSpan(StyleSpan(Typeface.BOLD), startCardTitleIndex, startCardTitleIndex + cardTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.textCardFront.text = frontSpannableString

            val backSpannableString = SpannableString(showBackPhotoText)
            val startBackIndex = showBackPhotoText.indexOf(getString(R.string.tiyende_authentication_step_card_back))
            val startCardBackTitleIndex = showBackPhotoText.indexOf(cardTitle)
            backSpannableString.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startBackIndex, startBackIndex + getString(R.string.tiyende_authentication_step_card_back).length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            backSpannableString.setSpan(ForegroundColorSpan("#FF3ED9AB".toColorInt()), startCardBackTitleIndex, startCardBackTitleIndex + cardTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            backSpannableString.setSpan(StyleSpan(Typeface.BOLD), startCardBackTitleIndex, startCardBackTitleIndex + cardTitle.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
            binding.textCardBack.text = backSpannableString
        }

        _binding?.let { binding ->
            imgFrontUrl = ""
            binding.vCardFrontMask.visibility = View.GONE
            binding.imgCardFrontUpload.setImageResource(R.mipmap.tiyende_card_upload_icon)
            binding.textCardFrontUpload.text = getString(R.string.tiyende_authentication_step_card_click_and_upload)

            imgBackUrl = ""
            binding.vCardBackMask.visibility = View.GONE
            binding.imgCardBackUpload.setImageResource(R.mipmap.tiyende_card_upload_icon)
            binding.textCardBackUpload.text = getString(R.string.tiyende_authentication_step_card_click_and_upload)

            when (stepTitle) {
                "pan_card_info" -> {
                    binding.imgCardFront.setImageResource(R.mipmap.tiyende_card_pan_front_default_icon)
                    binding.imgCardBack.setImageResource(R.mipmap.tiyende_card_pan_back_default_icon)
                    binding.cardBackLayout.visibility = View.INVISIBLE
                }
                "aadhaar_card_info" -> {
                    binding.imgCardFront.setImageResource(R.mipmap.tiyende_card_aadhaar_front_default_icon)
                    binding.imgCardBack.setImageResource(R.mipmap.tiyende_card_aadhaar_back_default_icon)
                    binding.cardBackLayout.visibility = View.VISIBLE
                }
                else -> {
                    binding.imgCardFront.setImageResource(R.mipmap.tiyende_card_pan_front_default_icon)
                    binding.imgCardBack.setImageResource(R.mipmap.tiyende_card_pan_back_default_icon)
                    binding.cardBackLayout.visibility = View.VISIBLE
                }
            }

            //提交按钮移到外层，通过通知的方式控制提交
            binding.btnCardInfoSave.visibility = View.INVISIBLE
        }
    }

    override fun initTiyendeListener() {
        _binding?.cardInfoDeleteLayout?.setOnClickListener {
            isShowDelete = !isShowDelete
            showTiyendeCardInfoDeleteTips()
        }
        //正面
        _binding?.cardFrontLayout?.setOnClickListener {
            isFront = true
            val eventRemark = "$stepTitle Front"
            showTiyendePhotoDialog(eventRemark)
        }
        //反面
        _binding?.cardBackLayout?.setOnClickListener {
            isFront = false
            val eventRemark = "$stepTitle Back"
            showTiyendePhotoDialog(eventRemark)
        }
        //提交
        _binding?.btnCardInfoSave?.setOnClickListener {
            onTiyendeSubmitAuthenticationInfoAction()
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = requireContext(), uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        TiyendeLogger.e(">>>>>>>album>>>>>>>>>>$localPath")

                        showTiyendeLoading()
                        if (upLoadPresenter == null){
                            upLoadPresenter = TiyendeImageUploadPresenter(this)
                        }
                        upLoadPresenter?.submitUploadImageAction(localPath)
                    }
                }
            } else {
                TiyendeLogger.e("No media selected")
            }
        }
    }

    override fun loadTiyendeData() {
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_START,stepTitle))
    }

    private fun showTiyendeCardInfoDeleteTips(){
        when(isShowDelete){
            true -> {
                _binding?.imgSelectDelete?.setImageResource(R.mipmap.tiyende_selfie_delete_tips_selected_icon)
            }
            else -> {
                _binding?.imgSelectDelete?.setImageResource(R.mipmap.tiyende_selfie_delete_tips_normal_icon)
            }
        }
    }

    /**
     * 图片上传成功
     */
    private fun showTiyendeUploadImageSuccess(imgPath: String, imgUrl: String) {
        _binding?.let { binding ->
            when(isFront){
                true -> {
                    imgFrontUrl = imgUrl
                    TiyendeImageUtil.instance?.loadImageUrl(requireContext(),binding.imgCardFront,imgPath)
                    binding.vCardFrontMask.visibility = View.VISIBLE
                    binding.imgCardFrontUpload.setImageResource(R.mipmap.tiyende_card_re_upload_icon)
                    binding.textCardFrontUpload.text = getString(R.string.tiyende_authentication_step_card_re_upload)
                    val eventRemark = "$stepTitle Front $$$imgUrl"
                    addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_UPLOAD_URL,eventRemark)
                }
                else -> {
                    imgBackUrl = imgUrl
                    TiyendeImageUtil.instance?.loadImageUrl(requireContext(),binding.imgCardBack,imgPath)
                    binding.vCardBackMask.visibility = View.VISIBLE
                    binding.imgCardBackUpload.setImageResource(R.mipmap.tiyende_card_re_upload_icon)
                    binding.textCardBackUpload.text = getString(R.string.tiyende_authentication_step_card_re_upload)
                    val eventRemark = "$stepTitle Back $$$imgUrl"
                    addEventPointRequestAction(TiyendeEventPointType.FORM.TIYENDE_FORM_UPLOAD_URL,eventRemark)
                }
            }
        }
    }

    /**
     * 拍照
     */
    private val startOpenCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                TiyendeLogger.e(">>>>>>onActivityResult: data = " + result.data)
                result.data?.let {
                    val imgLocalPath = it.getStringExtra("imgLocalPath").toString()
                    val imgUrl = it.getStringExtra("imgUrl").toString()
                    showTiyendeUploadImageSuccess(imgLocalPath,imgUrl)
                }
            }
        }
    }

    /**
     * 打开相机
     */
    private fun startOpenCameraAction(){
        val intent = Intent(context, TiyendeCameraCardActivity::class.java)
        intent.putExtra("pageName", stepTitle)
        startOpenCameraResultLauncher.launch(intent)
    }

    /**
     * 打开相册
     */
    private fun startOpenAlbumAction(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 相机、相册
     */
    private fun showTiyendePhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = TiyendePhotoDialog(requireContext(),eventRemark,object : TiyendePhotoDialog.IDialogCallback{
                override fun startCameraAction() {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA,eventRemark)
                    if (CommonPermissions.isGranted(requireContext(),Permission.CAMERA)){
                        startOpenCameraAction()
                    } else {
                        showTiyendePermissionReasonDialog()
                    }
                }

                override fun startAlbumAction() {
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_ALBUM,eventRemark)
                    startOpenAlbumAction()
                }
            })
            photoDialog?.setCancelable(true)
            photoDialog?.setCanceledOnTouchOutside(true)
        }
        photoDialog?.show()
    }

    /**
     * 模拟权限声明dialog
     */
    fun showTiyendePermissionReasonDialog(){
        val item = TiyendePermissionHelper.queryTiyendeCameraItem()
        val reasonDialog = TiyendePermissionReasonDialog(requireContext(),stepTitle,object: TiyendePermissionReasonDialog.IDialogCallback{
            override fun onTiyendePermissionDenyClick() {
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_DENY,Permission.CAMERA)
            }
            override fun onTiyendePermissionAgreeClick() {
                addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_AGREE,Permission.CAMERA)
                requestTiyendePermissionAction()
            }
        })
        reasonDialog.setCancelable(true)
        reasonDialog.setCanceledOnTouchOutside(true)
        reasonDialog.show()
        reasonDialog.showTiyendePermissionReasonItem(item)
    }

    /**
     * 申请权限
     */
    private fun requestTiyendePermissionAction(){
        CommonPermissions.with(this)
            .permission(Permission.CAMERA)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        startOpenCameraAction()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    CommonPermissions.startPermissionActivity(requireContext(),Permission.CAMERA)
                }
            })
    }

    /**
     * 图片上传成功
     */
    override fun showTiyendeImageUploadSuccess(imgPath: String, imgUrl: String) {
        showTiyendeUploadImageSuccess(imgPath,imgUrl)
    }

    /**
     * 数据安全提示
     */
    private fun showCardInfoDeleteTipsDialog(params: JSONObject){
        val sendSuccessDialog = TiyendeSuccessDialog(requireContext())
        sendSuccessDialog.setCancelable(true)
        sendSuccessDialog.setCanceledOnTouchOutside(false)
        sendSuccessDialog.show()
        sendSuccessDialog.showSuccessTips(getString(R.string.tiyende_selfie_delete_success_tips))
        Handler(Looper.getMainLooper()).postDelayed({
            if (isAdded && !requireActivity().isFinishing && sendSuccessDialog.isShowing) {
                sendSuccessDialog.dismiss()
            }
            submitTiyendeCardInfoAction(params)
        },2000)
    }

    /**
     * 提交
     */
    private fun submitTiyendeCardInfoAction(params: JSONObject){
        val act = getAct() as TiyendeAuthenticationStepsActivity
        act.onAuthenticationStepSubmitAction(params)
    }

    /**
     * 提交进件信息
     */
    private fun onTiyendeSubmitAuthenticationInfoAction(){
        _binding?.root?.clearFocus()
        addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_NEXT, stepTitle),"")
        if (imgFrontUrl.isEmpty()){
            showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error), stepTitle)
            return
        }
        // aadhaar card 必传反面
        if (stepTitle == "aadhaar_card_info" && imgBackUrl.isEmpty()){
            showErrorTipsDialog(getString(R.string.tiyende_dialog_tips_submit_error), stepTitle)
            return
        }
        val params = JSONObject().addCommonParams()
        when(stepTitle){
            "pan_card_info" -> {// v1/panCardInfo
                params.put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_PAN_CARD_PATH)
                params.put("panCardImg",imgFrontUrl)
                params.put("panCardBackImg",imgBackUrl)
            }
            "aadhaar_card_info" -> {// v1/addrProofInfo
                params.put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_AADHAAR_CARD_PATH)
                params.put("frontImg",imgFrontUrl)
                params.put("backImg",imgBackUrl)
            }
        }
        // TODO: Step Next 批量埋点上报
        TrackPointManager.getInstance().manualReport()

        if (isShowDelete){
            showCardInfoDeleteTipsDialog(params)
        } else {
            submitTiyendeCardInfoAction(params)
        }
    }

    override fun onTiyendePublishEvent(event: TiyendeEventData) {
        super.onTiyendePublishEvent(event)
        when(event.eventType){
            TiyendeEventData.TYPE.TIYENDE_SUBMIT_AUTHENTICATION -> {
                onTiyendeSubmitAuthenticationInfoAction()
            }
            else -> {
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(String.format(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_XX_END,stepTitle),"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}